package main

import (
	"aglaia/global"
	"aglaia/internal/model"
	"aglaia/internal/routers"
	"aglaia/pkg/job"
	"aglaia/pkg/logger"
	"aglaia/pkg/setting"
	"github.com/gin-gonic/gin"
	"gopkg.in/natefinch/lumberjack.v2"
	"log"
	"net/http"
	"time"
)

func init() {
	if err := setupSetting(); err != nil {
		log.Fatalf("init.setupSetting err: %v", err)
	}
	if err := setupLogger(); err != nil {
		log.Fatalf("init.setupLogger err: %v", err)
	}
	if err := setupDatabase(); err != nil {
		log.Fatalf("init.setupDatabase err: %v", err)
	}
	// 邮件通知
	job.EmailJob()
}

func main() {
	r := routers.NewRouter()
	gin.SetMode(global.ServerSetting.RunMode)
	s := &http.Server{
		Addr:           ":" + global.ServerSetting.HttpPort,
		Handler:        r,
		ReadTimeout:    global.ServerSetting.ReadTimeout,
		WriteTimeout:   global.ServerSetting.WriteTimeout,
		MaxHeaderBytes: 1 << 20,
	}

	if err := s.ListenAndServe(); err != nil {
		log.Fatalf("main.ListenAndServe err: %v", err)
	}

}

func setupSetting() error {
	st, err := setting.NewSetting()
	if err != nil {
		return err
	}
	if err := st.ReadSection("Server", &global.ServerSetting); err != nil {
		return err
	}
	if err := st.ReadSection("App", &global.AppSetting); err != nil {
		return err
	}
	if err := st.ReadSection("Database", &global.DatabaseSetting); err != nil {
		return err
	}
	if err := st.ReadSection("JWT", &global.JWTSetting); err != nil {
		return err
	}

	global.ServerSetting.ReadTimeout *= time.Second
	global.ServerSetting.WriteTimeout *= time.Second
	global.JWTSetting.Expire *= time.Second
	global.AppSetting.UploadImageMaxSize *= 1024 * 1024

	return nil
}

func setupLogger() error {
	global.Logger = logger.NewLogger(&lumberjack.Logger{
		Filename:  global.AppSetting.LogSavePath + "/" + global.AppSetting.LogFileName + global.AppSetting.LogFileExt,
		MaxSize:   600,
		MaxAge:    10,
		LocalTime: true,
	}, "", log.LstdFlags)
	return nil
}

func setupDatabase() (err error) {
	global.DB, err = model.NewDBEngine(global.DatabaseSetting)
	if err != nil {
		return err
	}

	return nil
}
